package com.servlet;

import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;

import sun.misc.BASE64Encoder;

public class Download1Servlet extends HttpServlet {


	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		/*
		 * 两个头一个流
		 * Content—Type:
		 * Content-Disposition
		 */
		String filename = "F:/temp/罪恶王冠.ape";
		//String framename = new String("罪恶王冠".getBytes("UTF-8"), "ISO-8859-1");
		String framename = filenameEncoding("罪恶王冠", request);
		String contentType = this.getServletContext().getMimeType(filename);//获得文件MIME类型
		//准备输出流
		ServletOutputStream output = response.getOutputStream();
		//设置输出头
		response.setHeader("Content-Type", contentType);
		response.setHeader("Content-Disposition", "attachment;filename=" + framename);
		//准备输入流，写入到客户端
		FileInputStream input = new FileInputStream(filename);
		//将输出流的数据拷贝带输入流
		IOUtils.copy(input, output);
	}

	//转码
	public static String filenameEncoding(String filename, HttpServletRequest request) throws IOException {
		String agent = request.getHeader("User-Agent"); //获取浏览器
		if (agent.contains("Firefox")) {
			BASE64Encoder base64Encoder = new BASE64Encoder();
			filename = "=?utf-8?B?"
					+ base64Encoder.encode(filename.getBytes("utf-8"))
					+ "?=";
		} else if(agent.contains("MSIE")) {
			filename = URLEncoder.encode(filename, "utf-8");
		} else {
			filename = URLEncoder.encode(filename, "utf-8");
		}
		return filename;
	}
}
